/*
 * axios 二次封装
 */
import axios, { AxiosResponse } from "axios";
import { ElMessage } from "element-plus";
import config from "../config";
import router from "../router";
import storage from "./storage";

const TOKEN_INVALID = "登录身份过期，请重新登录";
const NETWORK_ERROR = "网络请求异常，请稍后重试";

interface IOptionsType {
  url: string;
  method?: string;
  mock?: boolean;
  params?: any;
  data?: any;
}

// 创建axios 实例对象 添加全局配置
const service = axios.create({
  baseURL: config.baseApi,
  timeout: 8000,
});

// 请求拦截

service.interceptors.request.use((req) => {
  // token
  if (req.url !== "/login") {
    const header = req.headers || {};
    const { token } = storage.getItem("userInfo") || "";
    if (!header.Authorization) header.Authorization = "Bearer " + token;
    return req;
  } else {
    return req;
  }
});

// 响应拦截 状态码 弹窗
service.interceptors.response.use((res: AxiosResponse<any, any>) => {
  const { code, msg } = res.data;

  if (code >= 200 && code < 300) {
    if (msg) ElMessage.success(msg);
    return res.data;
  } else if (code === 50001) {
    ElMessage.error(msg || TOKEN_INVALID);
    setTimeout(() => {
      router.push("/login");
    }, 1000);
    return Promise.reject(TOKEN_INVALID || msg);
  } else {
    ElMessage.error(msg || NETWORK_ERROR);
    return Promise.reject(msg || NETWORK_ERROR);
  }
});

/**
 * 发送请求
 * @param {IOptionsType} options 请求配置
 * @returns
 */

function request(options: IOptionsType) {
  let isMock = config.mock;
  options.method = options.method || "get";

  if (options.method.toUpperCase() === "GET") {
    options.params = options.data;
  }
  if (typeof options.mock !== "undefined") {
    isMock = options.mock;
  }
  if (config.env === "production") {
    service.defaults.baseURL = config.baseApi;
  } else {
    service.defaults.baseURL = isMock ? config.mockApi : config.baseApi;
  }
  console.log(
    config.env,
    service.defaults.baseURL,
    config.env === "production"
  );

  return service(options);
}

export default request;
